import { saveCar, getCar } from '@/utils/auth'
import { Toast } from 'vant'

export function add(id) {
  let goods = getCar()
  if (goods && goods !== 'false') {
    goods = JSON.parse(goods)
  } else {
    goods = {}
  }
  if (goods.hasOwnProperty(id)) {
      ++goods[id].num
  } else {
      goods[id] = {
          id: id,
          num: 1,
          pitch: true
      }
  }
  saveCar(goods)
}

export function reduce(id) {
  let goods = getCar()
  goods = JSON.parse(goods)
  if (goods[id].num === 1) {
    Toast.fail({message: '不能再减了', duration: 2000})
    return
  }
  --goods[id].num
  saveCar(goods)
}

export function changeGoodNum(id, num) {
  if (num == 0) {
    Toast.fail({message: '数量要大于0', duration: 2000})
    return
  }
  let goods = getCar()
  goods = JSON.parse(goods)
  goods[id].num = num
  saveCar(goods)
}

export function removeGood(id) {
  let goods = getCar()
  goods = JSON.parse(goods)
  delete goods[id]
  if (Object.keys(goods).length === 0) {
    goods = false
  }
  saveCar(goods)
}

export function removeSelectGood() {
  let goods = getCar()
  goods = JSON.parse(goods)
  for(const index in goods) {
    if (goods[index].pitch) {
      delete goods[index]
    }
  }

  if (Object.keys(goods).length === 0) {
    goods = false
  }
  saveCar(goods)
}


export function checkGood(id) {
  let goods = getCar()
  goods = JSON.parse(goods)
  goods[id].pitch = !goods[id].pitch
  saveCar(goods)
}

export function checkAllGood(check) {
  let goods = getCar()
  goods = JSON.parse(goods)
  for(const index in goods) {
    goods[index].pitch = check
  }
  saveCar(goods)
}

export function isInCar(id) {
  let goods = getCar()
  goods = JSON.parse(goods)
  for(const index in goods) {
    if (goods[index].id == id) {
      return true
    }
  }

  return false
}
